<template>
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="visible" @close="close">
    <el-form ref="form" :model="form" label-width="auto">
      <el-form-item :loading="loading" label="塘号：" prop="ncWarehouseid" :rules="{
    required: true,
    message: '请选择塘号',
  }">
        <el-select @change="handleChangeFishPond" v-model="form.ncWarehouseid" filterable placeholder="请选择塘号">
          <el-option v-for="item in stordocList" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item v-for="(item, index) in inputList" :key="index" :label="item.label + '：'" :prop="item.key">
        <el-input type="number" v-model="form[item.key]" :placeholder="'请输入' + item.label" />
      </el-form-item>
      <el-form-item label="日期：" prop="accumulationDate" :rules="{
    required: true,
    message: '请选择日期',
  }">
        <el-date-picker  :picker-options="pickerOptions" :disabled="currentItem !== null" v-model="form.accumulationDate" type="date" placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="confirm">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import ncWaterQualityApi from "@/api/module/ncWaterQuality";
import EnvironmentalDataMonitoringApi from "@/api/iot-monitoring/environmental-data-monitoring";     // 折线图获取
export default {
  components: {},
  props: {
    currentItem: {
      type: Object,
      required: false,
      default: () => {
        return null;
      },
    },
    value: {
      type: Boolean,
      default: false,
    },
    stordocList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    fishPondObj: {
      type: Object,
      required: false,
      default: () => {
        return {};
      },
    },
  },
  computed: {
    title() {
      return this.currentItem === null ? "新增" : "修改";
    },
  },
  data() {
    return {
      inputList: [
        {
          key: "ph",
          label: "PH",
        },
        {
          key: "oxygen",
          label: "溶解氧",
        },
        {
          key: "nitrogen",
          label: "氨氮",
        },
        {
          key: "subsalt",
          label: "亚盐",
        },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      formDefault: {
        ncWarehouseid: "",
        ph: "",
        oxygen: "",
        nitrogen: "",
        subsalt: "",
        accumulationDate: new Date(),
      },
      form: {},
      visible: false,
      loading: false,
      uploadPictureList: [],
    };
  },
  watch: {
    value(v) {
      this.visible = v;
      if (v) {
        this.init();
      }
    },
  },
  created() {
    this.reset();
  },
  methods: {
    handleChangeFishPond(e) {
      console.log(this.fishPondObj)
      console.log(this.fishPondObj[e])
      this.$set(this.form, 'ph', '');//PH
      this.$set(this.form, 'oxygen', '');//溶解氧
      this.$set(this.form, 'nitrogen', '');//氨氮
      this.$set(this.form, 'subsalt', '');//亚盐
      if (!this.fishPondObj[e]) {
        console.log('该鱼塘未关联生产设施')
      } else {
        console.log('正在查询物联数据项...');
        this.queryDataItem(this.fishPondObj[e])
      }
    },
    hasNumber() {
      let list = this.inputList.map(e => {
        return this.form[e.key] ? Number(this.form[e.key]) : undefined
      })
      return list.some(e => { return typeof e == 'number' })
    },
    queryDataItem(e) {
      this.loading = true;
      EnvironmentalDataMonitoringApi.queryNewByFishPondId({ fishPondId: e }).then(res => {
        this.loading = false;
        let dataList = res.data || [];
        let dataItemList = dataList.filter(item => {
          return item.dataType && item.dataType.mainingControlType == "COLLECTION"
        })
        if (res.success && dataItemList.length > 0) {
          let phObj = dataItemList.find(e => {
            return e.dataType.dataTypeName.includes('PH') ||
              e.dataType.dataTypeName.includes('ph') ||
              e.dataType.dataTypeName.includes('pH') ||
              e.dataType.dataTypeName.includes('Ph') ||
              e.dataType.dataTypeName.includes('酸碱度')
          });
          let oxygenObj = dataItemList.find(e => {
            return e.dataType.dataTypeName.includes('氧') ||
              e.dataType.dataTypeName.includes('含氧量')
          });
          this.$set(this.form, 'ph', phObj.dataCollectNew.firstValue || 0.00);//PH
          this.$set(this.form, 'oxygen', oxygenObj.dataCollectNew.firstValue || 0.00);//溶解氧
          this.$set(this.form, 'nitrogen', ''); //氨氮
          this.$set(this.form, 'subsalt', ''); //亚盐
        } else {
          this.$set(this.form, 'ph', '');//PH
          this.$set(this.form, 'oxygen', '');//溶解氧
          this.$set(this.form, 'nitrogen', '');//氨氮
          this.$set(this.form, 'subsalt', '');//亚盐
        }
      }).then(err => {
        this.loading = false;
      });
    },
    reset() {
      this.form = { ...this.formDefault };
      this.$refs.form && this.$refs.form.resetFields();
    },
    init() {
      const { currentItem, form } = this;
      if (currentItem) {
        Object.keys(form).forEach((key) => {
          if (currentItem.hasOwnProperty(key)) {
            form[key] = currentItem[key];
          }
        });
        form.content = "";
      }
    },
    // 关闭
    close() {
      setTimeout(() => {
        this.reset();
      }, 250);
      this.$emit("close");
    },
    // 取消
    cancel() {
      this.$emit("input", false);
    },
    // 确认
    confirm() {
      if (this.hasNumber()) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const { form, currentItem, stordocList } = this;
            const formCopy = JSON.parse(JSON.stringify(form));
            formCopy.accumulationDate = this.$moment(formCopy.accumulationDate).format("YYYY-MM-DD")
            let paylod = {
              ...formCopy,
              ncWarehousename: stordocList.find(
                (i) => i.code === formCopy.ncWarehouseid
              ).name,
            };
            const currentApi =
              currentItem === null
                ? ncWaterQualityApi.add
                : ncWaterQualityApi.edit;
            if (currentItem !== null) {
              paylod = {
                ...currentItem,
                ...paylod,
              };
            }
            this.loading = true;
            currentApi(paylod)
              .then((res) => {
                if (res.success) {
                  this.$message({
                    type: "success",
                    message: currentItem === null?"添加成功":"编辑成功",
                  });
                  this.close();
                  this.$emit("reflash");
                } else {
                  this.$message({
                    type: "info",
                    message: res.message || "操作失败",
                  });
                }
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      } else {
        this.$message.info('至少填写一个数据项')
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}

.el-date-editor {
  width: 100%;
}
</style>
